<?php

declare(strict_types=1);

namespace app\index\controller;

use app\common\model\Assets;
use app\common\model\User;
use app\common\model\DealOrder;
use app\common\model\Deal as DealModel;
use app\common\tool\Result;
use think\exception\ValidateException;
use think\facade\View;
use app\common\controller\Config;

class Deal extends Base
{
    /**
     * 交易大厅
     */
    public function index()
    {
        $param = $this->request->get();
        $sys = Config::lists();
        $buy_money = $sys['buy_money'];
        if (isset($param['id'])) {
            $info = DealModel::find($param['id']);
            if (!empty($info)) {
                $buy_money = $info['price'];
            }
        }
        View::assign(
            [
                'buy_money' => $buy_money,
            ]
        );
        return View::fetch();
    }
    /**
     * 获取交易列表
     */
    public function getList()
    {
        try {
            $param = $this->request->get();
            $map[] = ['status', '=', 1];
            $map[] = ['type', '=', $param['type']];
            $map[] = ['uid', '<>', $this->user->id];
            $ids =  DealModel::where($map)->column('id,num');
            $lisid = [];
            foreach ($ids as $k => $v) {
                $num = DealOrder::where(['deal_id' => $v['id']])->sum('num');
                if ($v['num'] - $num > 0) {
                    $lisid[] = $v['id'];
                }
            }
            if (!empty($lisid)) {
                $map[] = ['id', 'in', $lisid];
                $list = DealModel::getPageList(
                    $map,
                    'id,uid,price,num,money,create_time,type',
                    $this->getPage(),
                    $this->getLimit(),
                    false,
                    ['user']
                );
                foreach ($list['data'] as $k => $v) {
                    $v->is_buy = $v->uid == $this->user->id ? 1 : 2;
                    $num = DealOrder::where(['deal_id' => $v->id])->sum('num');
                    $money = DealOrder::where(['deal_id' => $v->id])->sum('money');
                    $v->n_count = $v->num - $num > 0 ? $v->num - $num : 0;
                    $v->money = $v->money - $money > 0 ? $v->money - $money : 0;
                    $v->is_full = $v->num <= $num ? 1 : 2;
                    $list['data'][$k] = $v;
                }
            }else{
                $list = ['code'=>1,'data' => []];
            }
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 提交交易
     */
    public function add()
    {
        try {
            if (empty($this->user->mobile)) {
                return Result::fail('请先到 个人资料完善手机号');
            }
            $param = $this->request->post();
            $this->validate($param, 'Deal');
            return Result::fastReturn(DealModel::add($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 撤销交易
     */
    public function repeal()
    {
        try {
            $open = get_trade_status(2);
            if ($open['code'] == 0) {
                return Result::fail($open['msg']);
            }
            $param = $this->request->post();
            return Result::fastReturn(DealModel::repeal($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 我的交易
     */
    public function my_deal_list()
    {
        return View::fetch();
    }
    /**
     * 我的交易列表
     */
    public function getDealList()
    {
        try {
            $param = $this->request->get();
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
            if (isset($param['type']) && $param['type']) {
                if ($param['type'] == 2) {
                    $map[] = ['uid', '=', $this->user->id];
                } else {
                    $map[] = ['buy_uid', '=', $this->user->id];
                }
            }
            $list = DealOrder::getPageList(
                $map,
                '*',
                $this->getPage(),
                $this->getLimit(),
                false,
                ['buser', 'user'],
                [],
                [],
                [],
                [],
                '',
                ['statusText']
            );
            foreach ($list['data'] as &$v) {
                $v->types =  intval($param['type']);
            }
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 交易单编辑操作
     */
    public function edit()
    {
        try {
            $open = get_trade_status(2);
            if ($open['code'] == 0) {
                return Result::fail($open['msg']);
            }
            $param = $this->request->post();
            return Result::fastReturn(DealOrder::edit($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 支付打款
     */
    public function payment()
    {
        $param = $this->request->get();
        $info = DealOrder::where('id', $param['id'])->with(['user'])->find();
        $user = User::where('id', $info['uid'])->find();
        $ali = [];
        $wechat = [];
        $bank = [];
        if ($user['alipay_image']) {
            $ali = [[
                'title' => '支付宝',
                'code' => '',
                'icon' => '/static/index/img/icon4.png',
                'class' => 'alipay',
                'img' => $user['alipay_image'],
            ]];
        }
        if ($user['wechat_image']) {
            $wechat = [[
                'title' => '微信',
                'code' => '',
                'icon' => '/static/index/img/icon3.png',
                'class' => 'wechat',
                'img' => $user['wechat_image'],
            ]];
        }
        if ($user['bank_number']) {
            $bank = [[
                'title' => '银行卡',
                'code' => [
                    $user['bank_name'],
                    $user['bank_open'],
                    $user['bank_account_name'],
                    $user['bank_number'],
                ],
                'icon' => '/static/index/img/icon17.png',
                'class' => 'recharge-bank',
                'img' => '',
            ]];
        }
        $pay_list = array_merge($ali, $wechat, $bank);
        // print('<pre>');print_r($pay_list);die;
        View::assign(
            [
                'info' => $info,
                'pay_list' => $pay_list,
            ]
        );
        return View::fetch();
    }
    /**
     * 打款
     */
    public function pay()
    {
        try {
            $open = get_trade_status(2);
            if ($open['code'] == 0) {
                return Result::fail($open['msg']);
            }
            $param = $this->request->post();
            $user = $this->user;
            if (md5($param['pay_password']) != $user['pay_password']) {
                return ['code' => -1, 'msg' => '支付密码错误'];
            }
            $info = DealOrder::where('id', $param['id'])->with(['user'])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '交易不存在'];
            }
            if ($info->status != 1) {
                return ['code' => -1, 'msg' => '状态错误'];
            }
            $info->status = 2;
            $info->pay_way = $param['pay_way'];
            $info->images = $param['images'];
            $info->pay_time = time();
            $info->save();
            return Result::fastReturn(['code' => 1, 'msg' => '打款成功！', 'url' => url('deal/my_deal_list')->build() . '?type=1&status=2']);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 我的发布
     */
    public function my_deal_publish()
    {
        return View::fetch();
    }
    /**
     * 我的发布列表
     */
    public function getDealPublish()
    {
        try {
            $param = $this->request->get();
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
            if (isset($param['type']) && $param['type']) {
                $map[] = ['type', '=', $param['type']];
            }
            $map[] = ['uid', '=', $this->user->id];
            $list = DealModel::getPageList(
                $map,
                '*',
                $this->getPage(),
                $this->getLimit(),
                false,
                ['user'],
                [],
                [],
                [],
                [],
                '',
                ['statusText', 'end_num', 'end_money']
            );
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 交易详情
     */
    public function my_deal_detail()
    {
        return View::fetch();
    }
    /**
     * 交易详情列表
     */
    public function getDetailList()
    {
        try {
            $param = $this->request->get();
            $map[] = ['deal_id', '=', $param['type']];
            $list = DealOrder::getPageList(
                $map,
                '*',
                $this->getPage(),
                $this->getLimit(),
                false,
                ['buser', 'user'],
            );
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * 交易详情
     */
    public function my_deal_info()
    {
        $param = $this->request->get();
        $info = DealOrder::where('id', $param['id'])->with(['user', 'buser'])->append(['statusText'])->find();
        View::assign(
            [
                'info' => $info,
            ]
        );
        return View::fetch();
    }
}
